﻿using Android.App;
using Android.Content;
using Android.Hardware;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using AndroidX.Core.App;
using MiPadAndroid.Models;
using MiPadAndroid.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Provider;
using Xamarin.Essentials;
using Android.Media;
using Newtonsoft.Json;
using Android.Graphics;
using System.Threading;

namespace MiPadAndroid
{
    [Activity(Label = "HomeActivity")]
    public class HomeActivity : Activity, ISensorEventListener
    {
        string NotificationTitle { get; set; } = "家庭助理";
        const string CHANNEL_ID = "CHANNEL_ID";
        const int notificationId = 0;

        AudioManager audioManager = null;
        PayloadMessage payloadMessage;
        DelayAction delayAction = new DelayAction();
        MqttService mqttService;
        string DeviceID = Android.Provider.Settings.Secure.GetString(Android.App.Application.Context.ContentResolver, Android.Provider.Settings.Secure.AndroidId);

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_home);
            TextView textView = this.FindViewById<TextView>(Resource.Id.textView1);
            textView.Text = DeviceID;
            // Create your application here

            audioManager = this.GetSystemService(Context.AudioService) as AudioManager;
            payloadMessage = new PayloadMessage();
            payloadMessage.Type = "update";
            payloadMessage.DeviceID = DeviceID;
            payloadMessage.Host = MqttService.GetIP();
            payloadMessage.Name = DeviceInfo.Name;
            payloadMessage.Model = DeviceInfo.Model;
            payloadMessage.DeviceVersion = DeviceInfo.VersionString;
            payloadMessage.AppVersion = AppInfo.VersionString;

            DeviceDisplay.KeepScreenOn = true;
            CreateNotificationChannel();
            string ip = this.Intent.GetStringExtra("ip");
            mqttService = new MqttService(ip);
            mqttService.OnConnected += (s, e) =>
            {
                NotificationTitle = "MQTT连接成功";
                AddNotification("MQTT连接成功");
                mqttService.Subscribe($"android/{DeviceID}");
            };
            mqttService.OnDisconnected += (s, e) =>
            {
                NotificationTitle = "MQTT断开连接";
                AddNotification("MQTT断开连接");
            };
            mqttService.OnMessage += async (s, e) =>
            {
                MQTTnet.MqttApplicationMessage msg = s as MQTTnet.MqttApplicationMessage;
                if(msg.Payload != null)
                {
                    string topic = msg.Topic;
                    string text = System.Text.Encoding.UTF8.GetString(msg.Payload);
                    PayloadMessage payload = JsonConvert.DeserializeObject<PayloadMessage>(text);
                    switch (payload.Type)
                    {
                        case "tts":
                            await TextToSpeech.SpeakAsync(payload.Data);
                            break;
                        case "clipboard":
                            if (string.IsNullOrEmpty(payload.Data))
                            {
                                payloadMessage.Data = await Clipboard.GetTextAsync();
                            }
                            else
                            {
                                await Clipboard.SetTextAsync(payload.Data);
                            }
                            break;
                        case "ScreenBrightness":
                            Settings.System.PutInt(this.ContentResolver, Settings.System.ScreenBrightness, payload.ScreenBrightness ?? 200);
                            break;
                        case "SystemVolume":
                            audioManager.SetStreamVolume(Stream.Music, payload.SystemVolume ?? 5, VolumeNotificationFlags.PlaySound);
                            break;
                        case "LockScreen":
                            FloatWindow(payload.LockScreen ?? false);
                            payloadMessage.LockScreen = payload.LockScreen;
                            break;
                    }
                }
            };
            mqttService.Connect();
            SensorManager sensorManager = GetSystemService(Context.SensorService) as SensorManager;
            sensorManager.RegisterListener(this, sensorManager.GetDefaultSensor(SensorType.Light), SensorDelay.Fastest);
        }

        #region 通知
        void CreateNotificationChannel()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                // Notification channels are new in API 26 (and not a part of the
                // support library). There is no need to create a notification
                // channel on older versions of Android.
                return;
            }

            var channelName = "通道名称";
            var channelDescription = "通道描述";
            var channel = new NotificationChannel(CHANNEL_ID, channelName, NotificationImportance.Default)
            {
                Description = channelDescription
            };

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.CreateNotificationChannel(channel);
        }
        // 添加通知
        public void AddNotification(string text)
        {
            // Instantiate the builder and set notification elements:
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .SetContentTitle($"{DateTime.Now.ToString("HH:mm:ss")} {mqttService.ConnectionState}{NotificationTitle}")
                .SetContentText(text)
                .SetSmallIcon(Resource.Drawable.abc_ic_ab_back_material);

            // Build the notification:
            Notification notification = builder.Build();

            // Get the notification manager:
            NotificationManager notificationManager =
                GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            notificationManager.Notify(notificationId, notification);
        }
        #endregion

        #region 传感器
        public void OnAccuracyChanged(Sensor sensor, [GeneratedEnum] SensorStatus accuracy)
        {

        }

        public void OnSensorChanged(SensorEvent e)
        {
            // 光照传感器
            if (e.Sensor.Name.Contains("Light Sensor"))
            {
                payloadMessage.LightSensor = e.Values[0];
                this.AddNotification($"当前光照：{payloadMessage.LightSensor}");
                // 信息上报
                delayAction.Throttle(1000, null, new Action(() => {
                    // 电量     
                    payloadMessage.BatteryLevel = Convert.ToInt32(Battery.ChargeLevel * 100);
                    // 充电状态
                    payloadMessage.BatteryState = Battery.State.ToString();
                    payloadMessage.PowerSource = Battery.PowerSource.ToString();
                    // 音量
                    payloadMessage.SystemVolume = audioManager.GetStreamVolume(Stream.Music);
                    payloadMessage.SystemMaxVolume = audioManager.GetStreamMaxVolume(Stream.Music);
                    // 屏幕亮度
                    payloadMessage.ScreenBrightness = Settings.System.GetInt(this.ContentResolver, Settings.System.ScreenBrightness);
                    mqttService.Publish("android/info", payloadMessage);
                }));
            }
        }
        #endregion

        #region 全屏浮动按钮

        Button floatButton = null;
        Timer timer = null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="flags">显示黑屏：true,  关闭黑屏：false</param>
        void FloatWindow(bool flags)
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                if (floatButton == null)
                {
                    WindowManagerLayoutParams layoutParams = new WindowManagerLayoutParams();
                    // 判断当前Android系统版本
                    if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
                    {
                        layoutParams.Type = WindowManagerTypes.ApplicationOverlay;
                    }
                    else
                    {
                        layoutParams.Type = WindowManagerTypes.SystemError;
                    }
                    layoutParams.Format = Format.Rgba8888;
                    layoutParams.Gravity = GravityFlags.Left | GravityFlags.Top;
                    layoutParams.Flags = WindowManagerFlags.Fullscreen | WindowManagerFlags.TranslucentStatus | WindowManagerFlags.TranslucentNavigation;

                    // 窗口的宽高和位置
                    DisplayMetrics dm = new DisplayMetrics();
                    WindowManager.DefaultDisplay.GetMetrics(dm);
                    layoutParams.Width = dm.WidthPixels;
                    layoutParams.Height = dm.HeightPixels;
                    layoutParams.X = 0;
                    layoutParams.Y = 0;
                    // 生成一个按钮
                    floatButton = new Button(this.ApplicationContext);
                    // floatButton.Text = 
                    floatButton.Text = System.DateTime.Now.ToString("HH:mm:ss");
                    floatButton.SetTextSize(ComplexUnitType.Sp, 200);
                    floatButton.SetBackgroundColor(Color.Black);
                    floatButton.SetTextColor(Color.White);
                    floatButton.Click += (s, e) =>
                    {
                        WindowManager.RemoveView(floatButton);
                        timer.Dispose();
                        floatButton = null;
                    };
                    WindowManager.AddView(floatButton, layoutParams);

                    timer = new Timer((state) =>
                    {
                        MainThread.BeginInvokeOnMainThread(() =>
                        {
                            floatButton.Text = System.DateTime.Now.ToString("HH:mm:ss");
                        });
                    }, null, 0, 1000);
                }

                if (floatButton != null && !flags)
                {
                    WindowManager.RemoveView(floatButton);
                    timer.Dispose();
                    floatButton = null;
                }
            });
        }
        #endregion

    }
}